<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
 *
 * post-type-extensions.php template file
 *
 * (c) 2011 by Mike Walsh
 *
 * @author Mike Walsh <mike@walshcrew.com>
 * @package CASL-Soccer
 * @subpackage post-types
 * @version $Revision$
 * @lastmodified $Author$
 * @lastmodifiedby $Date$
 *
 */

/** Set up the post type(s) */
add_action('init', 'casl_register_post_types') ;

/** Register post type(s) */
function casl_register_post_types()
{
    /** Set up the arguments for the 'casl_player' post type. */
    $player_args = array(
        'public' => true,
        'query_var' => 'player',
        'rewrite' => array(
            'slug' => 'roster',
            'with_front' => true,
        ),
        'supports' => array(
            'title',
            'thumbnail',
            'editor',
            'exceprt'
        ),
        'labels' => array(
            'name' => 'Roster',
            'singular_name' => 'Player',
            'add_new' => 'Add New Player',
            'add_new_item' => 'Add New Player',
            'edit_item' => 'Edit Player',
            'new_item' => 'New Player',
            'view_item' => 'View Player',
            'search_items' => 'Search Roster',
            'not_found' => 'No Players Found',
            'not_found_in_trash' => 'No Players Found In Trash'
        ),
    );

    // Register the casl player post type
    register_post_type('player', $player_args) ;
}

//  Build custom meta box support
$prefix = 'casl_';

$casl_player_meta_box = array(
    'id' => 'player-profile-meta-box',
    'title' => 'Player Profile Details',
    'page' => 'player',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        array(
            'name' => 'Number',
            'desc' => 'Player\'s Jersey Number',
            'id' => $prefix . 'jersey_number',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'Position(s)',
            'desc' => 'List Player\'s Position(s)',
            'id' => $prefix . 'position',
            'type' => 'lgtext',
            'std' => ''
        ),
        array(
            'name' => 'Address',
            'desc' => 'Mailing Address - include City, State, and Zip Code',
            'id' => $prefix . 'address',
            'type' => 'textarea',
            'std' => ''
        ),
        array(
            'name' => 'Phone',
            'desc' => 'Player\'s Primary Phone Number',
            'id' => $prefix . 'phone',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'E-mail',
            'desc' => 'Player\'s Primary E-mail Address',
            'id' => $prefix . 'email',
            'type' => 'medtext',
            'std' => ''
        ),
        array(
            'name' => 'DOB',
            'desc' => 'Player\'s Date of Birth - use Month Day, Year format',
            'id' => $prefix . 'dob',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'Mother',
            'desc' => 'Mother\'s Name and E-mail Address',
            'id' => $prefix . 'mother',
            'type' => 'lgtext',
            'std' => ''
        ),
        array(
            'name' => 'Father',
            'desc' => 'Father\'s Name and E-mail Address',
            'id' => $prefix . 'father',
            'type' => 'lgtext',
            'std' => ''
        ),
        array(
            'name' => 'Height',
            'desc' => 'Player\'s Height',
            'id' => $prefix . 'height',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'Weight',
            'desc' => 'Player\'s Weight',
            'id' => $prefix . 'weight',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'Foot',
            'id' => $prefix . 'foot',
            'type' => 'select',
            'options' => array('Left', 'Right')
        ),
        array(
            'name' => 'School',
            'desc' => 'Player\'s School',
            'id' => $prefix . 'school',
            'type' => 'lgtext',
            'std' => ''
        ),
        array(
            'name' => 'Graduation Year',
            'desc' => 'Player\'s Graduation Year',
            'id' => $prefix . 'grad_year',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'GPA',
            'desc' => 'Grade Point Average',
            'id' => $prefix . 'gpa',
            'type' => 'smtext',
            'std' => ''
        ),
        array(
            'name' => 'Privacy',
            'id' => $prefix . 'privacy',
            'type' => 'select',
            'options' => array('Public', 'Private')
        ),
        array(
            'name' => 'Got Soccer Profile',
            'desc' => 'Player\'s Got-Soccer.com Profile Link',
            'id' => $prefix . 'gs_profile',
            'type' => 'lgtext',
            'std' => ''
        ),
        array(
            'name' => 'SIC Profile',
            'desc' => 'Player\'s Soccer-In-College.com Profile Link',
            'id' => $prefix . 'sic_profile',
            'type' => 'lgtext',
            'std' => ''
        ),
    )
);

add_action('admin_menu', 'casl_add_meta_box');

// Add meta box
function casl_add_meta_box() {
    global $casl_player_meta_box;

    $mb = &$casl_player_meta_box ;

    add_meta_box($mb['id'], $mb['title'], 'casl_show_meta_box', $mb['page'], $mb['context'], $mb['priority']);
}

// Callback function to show fields in meta box
function casl_show_meta_box()
{
    global $casl_player_meta_box, $post;

    $mb = &$casl_player_meta_box ;

    // Use nonce for verification
    echo '<input type="hidden" name="casl_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';

    echo '<table class="form-table">';

    foreach ($mb['fields'] as $field) {
        // get current post meta data
        $meta = get_post_meta($post->ID, $field['id'], true);

        echo '<tr>',
                '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
                '<td>';
        switch ($field['type']) {
            case 'text':
            case 'lgtext':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
                break;
            case 'medtext':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:47%" />', '<br />', $field['desc'];
                break;
            case 'smtext':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:27%" />', '<br />', $field['desc'];
                break;
            case 'textarea':
                echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
                break;
            case 'select':
                echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                foreach ($field['options'] as $option) {
                    echo '<option', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                }
                echo '</select>';
                break;
            case 'radio':
                foreach ($field['options'] as $option) {
                    echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                }
                break;
            case 'checkbox':
                echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
                break;
        }
        echo     '<td>',
            '</tr>';
    }

    echo '</table>';
}

add_action('save_post', 'casl_save_meta_box_data');

// Save data from meta box
function casl_save_meta_box_data($post_id)
{
    global $casl_player_meta_box ;

    $mb = &$casl_player_meta_box ;

    // verify nonce
    if (!wp_verify_nonce($_POST['casl_meta_box_nonce'], basename(__FILE__)))
    {
        return $post_id;
    }

    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    {
        return $post_id;
    }

    // check permissions
    if ('page' == $_POST['post_type'])
    {
        if (!current_user_can('edit_page', $post_id))
        {
            return $post_id;
        }
    }
    elseif (!current_user_can('edit_post', $post_id))
    {
        return $post_id;
    }

    foreach ($mb['fields'] as $field)
    {
        $new = $_POST[$field['id']];

        $old = get_post_meta($post_id, $field['id'], true);

        if ($new && $new != $old)
        {
            update_post_meta($post_id, $field['id'], $new);
        }
        elseif ('' == $new && $old)
        {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}

// Add to admin_init function
add_filter('manage_edit-player_columns', 'casl_add_new_player_columns');

/** Add more columns */
function casl_add_new_player_columns($cols)
{
    global $prefix ;

    //  The "Title" column is re-labeled as "Player"!
    $cols['title'] = 'Player' ;

	return array_merge(
		array_slice($cols, 0, 2),
        array(
            $prefix . 'jersey_number' => __('Jersey Number'),
            $prefix . 'position' => __('Position'),
        ),
        array_slice($cols, 2)
	) ;
}

/**  Retrieve the column content */
add_action('manage_posts_custom_column', 'casl_player_custom_columns', 10, 2) ;

function casl_player_custom_columns($column, $post_id)
{
    global $prefix ;

    switch ($column)
    {
        case $prefix . 'jersey_number':
            echo get_post_meta( $post_id, $prefix . 'jersey_number', true) ;
            break;
        case $prefix . 'position':
            echo get_post_meta( $post_id, $prefix . 'position', true) ;
            break;
    }
}
 
add_filter('manage_edit-player_sortable_columns', 'casl_player_sortable_columns') ;

// Make these columns sortable
function casl_player_sortable_columns()
{
    global $prefix ;

    return array(
        'title' => 'title',
        $prefix . 'jersey_number' => 'jersey_number',
    ) ;
}

/**  Output a Player's Profile Custom Fields */
function casl_player_custom_fields($post_id)
{
    global $prefix ;
    global $casl_player_meta_box ;

    $mb = &$casl_player_meta_box ;

    $output = '<div class="roster-player-profile">' ;
    $output .= get_the_post_thumbnail($post_id, 'rosterpage-headshot') ;

    //  Build a table to display the roster - it is the cleanest way ...
    $output .= '<table class="roster-player-profile">' ;
    $output .= '<thead>' ;
    $output .= '<tr class="roster-player-profile-row roster-player-profile-row-header">' ;
    $output .= '<th colspan="2">' . get_the_title() . '</th>' .
        PHP_EOL .  '</tr>' . PHP_EOL . '</thead>' . PHP_EOL . '<tbody>' ;
    //$output .= '</thead>' . PHP_EOL . '<tbody>' ;

    foreach ($mb['fields'] as $field)
    {
        // get current post meta data
        $meta = get_post_meta($post_id, $field['id'], true);

        //  Show the fields that aren't empty
        if ($meta != '')
        {
            $fieldclass = substr($field['id'], strlen($prefix)) ;
            $fieldlabel = ucwords(str_replace(array('_'), ' ', $fieldclass)) ;
            $output .= '<tr class="roster-player-profile-row roster-player-profile-row-' . $fieldclass . '">' ;
            $output .= '<th class="roster-player-' . $fieldclass . '">' . $fieldlabel . ':</th>' ;
            $output .= '<td class="roster-player-' . $fieldclass . '">' . $meta . '</td>' ;
            $output .= '</tr>' ;
        }
    }

    $output .= '</tbody>' . PHP_EOL . '</table>' ;

    $output .= get_the_content() ;

    $output .= '</div>' ;

    return $output ;
}
 
/** Set up the shortcode(s) */
add_action('init', 'casl_players_register_shortcodes') ;

/** Register shortcode(s) */
function casl_players_register_shortcodes()
{
    // Register the [player_players] shortcode
    add_shortcode('player_roster', 'casl_players_shortcode') ;
}

/**  [casl_players] shortcode */
function casl_players_shortcode()
{
    global $prefix ;

    // Query players from the database.
    $loop = new WP_Query(
        array(
            'post_type' => 'player',
            'order_by' => 'title',
            'order' => 'ASC',
            'posts_per_page' => -1,
        )
    ) ;

    //  Check to see if any players were returned.
    if ($loop->have_posts())
    {
        //  Build a table to display the roster - it is the cleanest way ...
        $output = '<table class="roster-players">' ;
        $output .= '<thead><tr><th>Jersey Number</th><th>Photo</th><th>Player Name</th><th>Position(s)</th></tr></thead>' ;
        $output .= '<tbody>' ;

        $plyrcnt = 0 ;

        //  Loop through the players (The Loop)
        while ($loop->have_posts())
        {
            $loop->the_post() ;

            $output .= sprintf('<tr class="player-roster-row player-roster-%s-row">',
                ($plyrcnt++ % 2) == 0 ? 'odd' : 'even') ;

            //  Output Jersey Number
            $output .= '<td class="player-roster-jersey-number">' . '<a href="' .  get_permalink() .
                '">' . get_post_meta( get_the_ID(), $prefix . 'jersey_number', true) . '</a></td>' ;
 
            //  Output Player Head Shot
            $output .= '<td class="player-roster-photo">' . '<a href="' .  get_permalink() .
                '">' .  get_the_post_thumbnail(null, 'rosterpage-thumb') . '</a></td>' ;
                //get_the_post_thumbnail(null, array(75, 100)) . '</td>' ;
 
            //  Display the Player's Name (title field)
            $output .= the_title(
                '<td class="player-roster-name"><a href="' . get_permalink() . '">', '</a></td>',
                false
            ) ;

            //  Output Position(s)
            $output .= '<td class="player-roster-position">' .
                get_post_meta( get_the_ID(), $prefix . 'position', true) . '</td>' ;
            $output .= '</tr>' ;
        }

        //  Close the unordered list
        $output .= '</tbody></table>' ;
    }
    else  //  No players found
    {
        $output = '<p>No players have been added to the roster.' ;
    }

    //  Return the list of players
    return $output ;
}

/**
 * Set up a footer hook to rearrange the post editing screen
 * for the 'player' custom post type.  The meta box which has all
 * of the custom fields in it will appear before the Visual Editor.
 * This is accomplished using a simple jQuery script once the
 * document is loaded.
 * 
 *
 */
function casl_admin_footer_hook()
{
    global $post ;

    if (get_post_type($post) == 'player')
    {
?>
<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#normal-sortables').insertBefore('#postdivrich') ;
    }) ;
</script>

<?php
    }
}

/**  Hook into the Admin Footer */
add_action('admin_footer','casl_admin_footer_hook');

?>
